package cn.wolfcode.trip.app.controller;

import cn.wolfcode.trip.app.util.UserContext;
import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.service.IUserService;
import cn.wolfcode.trip.base.util.JSONResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 会话资源控制器
 */
@RestController
@RequestMapping("sessions")
public class SessionController {

    @Autowired
    IUserService userService;

    /**
     * 创建会话(登录)
     * @return
     */
    @PostMapping
    public JSONResult login(@RequestParam String email,@RequestParam String password){
        JSONResult result = new JSONResult();
        try {
            User user = userService.login(email, password);
            //把user放入session中
            UserContext.setCurrentUser(user);
            //把用户的信息返回给客户端
            result.setResult(user);
        } catch (Exception e) {
            e.printStackTrace();
            result.mark(e.getMessage());
        }
        return result;
    }

    /**
     * 销毁会话(注销)
     * @return
     */
    @DeleteMapping
    public JSONResult logout(){
        JSONResult result = new JSONResult();
        UserContext.getSession().invalidate();
        return result;
    }
}
